/*
 * hkasm - A universal algebraic user defined assembler (for microcontrollers etc....)
 * Copyright (C) 2009  Henri Koskela <henri.koskela@iki.fi>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.Collections;
using System.IO;

class IntelHex8{
	private string filename;
		
	public IntelHex8(string file){
		this.filename=file;
	}
		
	public void save(ArrayList stringdata){	
		byte[] data = BinOperations.chanceByteEndian(BinOperations.toByteData(stringdata));			
		TextWriter tw = new StreamWriter(this.filename);
		tw.WriteLine(":020000020000FC");  //HEADER
		long offset=0;
		byte recordlength=16;//bytes
		long sum=0;
		
		while(offset<data.Length){
			string outputdata="";
			sum=(offset&0xFF)+(offset>>8);
			int j;
			long startoffset=offset;				
			for(j=0;j<Math.Min(recordlength,data.Length-startoffset);j++){
				sum+=data[offset];
				outputdata+=BinOperations.byte2hex(data[offset]);
				offset++;
			}
			sum+=j; //Recordlength
			tw.Write(":"+BinOperations.byte2hex((byte)(offset-startoffset))+BinOperations.byte2hex((byte)(startoffset>>8))+BinOperations.byte2hex((byte)(startoffset&0xFF))+"00");
			tw.Write(outputdata);
			tw.WriteLine(BinOperations.byte2hex((byte)((256-sum)&0xFF)));
		}
		tw.WriteLine(":00000001FF");
		tw.Close();
	}
}
